package com.boyiis.sell.service.impl;

import com.boyiis.sell.converter.Order2OrderDtoConverter;
import com.boyiis.sell.enums.OrderStatusEnum;
import com.boyiis.sell.enums.PayStatusEnum;
import com.boyiis.sell.enums.ResultEnum;
import com.boyiis.sell.exception.SellException;
import com.boyiis.sell.model.dto.CartDTO;
import com.boyiis.sell.model.dto.OrderDTO;
import com.boyiis.sell.model.entity.Order;
import com.boyiis.sell.model.entity.OrderDetail;
import com.boyiis.sell.model.entity.Product;
import com.boyiis.sell.repository.OrderDetailRepository;
import com.boyiis.sell.repository.OrderRepository;
import com.boyiis.sell.service.*;
import com.boyiis.sell.utils.KeyUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.transaction.Transactional;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Service
@Transactional
@Slf4j
public class OrderServiceImpl implements OrderService {
    @Autowired
    private OrderRepository orderRepo;

    @Autowired
    private OrderDetailRepository orderDetailRepo;

    @Autowired
    private ProductService productService;

    @Autowired
    private PayService payService;

    @Autowired
    private PushMessageService pushMessageService;

    @Autowired
    private WebSocket webSocket;

    @Override
    public OrderDTO create(OrderDTO orderDTO) {

        String orderId = KeyUtil.genUniqueKey();//创建orderId

        BigDecimal orderAmount = BigDecimal.ZERO;

        //1.查询商品
        for (OrderDetail orderDetail : orderDTO.getOrderDetailList()) {
            Product product = productService.findOne(orderDetail.getProductId());
            if (product == null) {
                throw new SellException(ResultEnum.PRODUCT_NOT_EXIST);
            }

            //2.计算总价
            orderAmount = orderAmount.add(product.getProductPrice().multiply(new BigDecimal(orderDetail.getProductQuantity())));

            //订单详情入库
            orderDetail.setDetailId(KeyUtil.genUniqueKey());
            orderDetail.setOrderId(orderId);
            BeanUtils.copyProperties(product, orderDetail);
            orderDetailRepo.save(orderDetail);
        }

        //3.写入订单数据库
        Order order = new Order();
        orderDTO.setOrderId(orderId);
        BeanUtils.copyProperties(orderDTO, order);
        order.setOrderAmount(orderAmount);
        order.setOrderStatus(OrderStatusEnum.NEW.getCode());
        order.setPayStatus(PayStatusEnum.WAIT.getCode());
        //4.扣库存
        List<CartDTO> cartDTOList = orderDTO.getOrderDetailList().stream()
                .map(e -> new CartDTO(e.getProductId(), e.getProductQuantity()))
                .collect(Collectors.toList());
        productService.decreaseStock(cartDTOList);
        orderRepo.save(order);

        //发送websoket消息
        webSocket.sendMessage("有新的订单");

        return orderDTO;
    }

    @Override
    public OrderDTO findOne(String orderId) {
        Order order = orderRepo.findOne(orderId);
        if (order == null) {
            throw new SellException(ResultEnum.ORDER_NOT_EXIST);
        }

        List<OrderDetail> orderDetailList = orderDetailRepo.findByOrderId(orderId);
        if (CollectionUtils.isEmpty(orderDetailList)) {
            throw new SellException(ResultEnum.ORDER_DETAIL_NOT_EXIST);
        }

        OrderDTO orderDTO = new OrderDTO();
        BeanUtils.copyProperties(order, orderDTO);
        orderDTO.setOrderDetailList(orderDetailList);
        return orderDTO;
    }

    @Override
    public Page<OrderDTO> findList(String buyerOpenid, Pageable pageable) {
        Page<Order> orderPage = orderRepo.findByBuyerOpenid(buyerOpenid, pageable);
        List<OrderDTO> orderDTOList = Order2OrderDtoConverter.convert(orderPage.getContent());
        Page<OrderDTO> orderDTOPage = new PageImpl<OrderDTO>(orderDTOList, pageable, orderPage.getTotalElements());
        return orderDTOPage;
    }

    @Override
    public Page<OrderDTO> findList(Pageable pageable) {
        Page<Order> orderPage = orderRepo.findAll(pageable);
        List<OrderDTO> orderDTOList = Order2OrderDtoConverter.convert(orderPage.getContent());
        Page<OrderDTO> orderDTOPage = new PageImpl<OrderDTO>(orderDTOList, pageable, orderPage.getTotalElements());
        return orderDTOPage;
    }

    @Override
    public OrderDTO cancel(OrderDTO orderDTO) {
        Order order = new Order();

        //判断订单状态
        if (!OrderStatusEnum.NEW.getCode().equals(orderDTO.getOrderStatus())) {
            log.error("【取消订单】订单状态不正确, orderId={}", orderDTO.getOrderId());
            throw new SellException(ResultEnum.ORDER_STATUS_ERROR);

        }
        //修改订单状态
        orderDTO.setOrderStatus(OrderStatusEnum.CANCEL.getCode());
        BeanUtils.copyProperties(orderDTO, order);
        order = orderRepo.save(order);
        if (null == order) {
            log.error("【取消订单】更新失败, orderId={}", orderDTO.getOrderId());
            throw new SellException(ResultEnum.ORDER_UPDATE_FAIL);
        }

        //返还库存
        if (CollectionUtils.isEmpty(orderDTO.getOrderDetailList())) {
            log.error("【取消订单】订单中无商品详情, orderId={}", orderDTO.getOrderId());
            throw new SellException(ResultEnum.ORDER_DETAIL_EMPTY);
        }
        List<CartDTO> cartDTOList = orderDTO.getOrderDetailList().stream().map(e -> new CartDTO(e.getProductId(), e.getProductQuantity())).collect(Collectors.toList());
        productService.increaseStock(cartDTOList);

        //如果已经支付，需要退款
        if (PayStatusEnum.FINISHED.equals(orderDTO.getPayStatus())) {
            payService.refund(orderDTO);
        }

        return orderDTO;
    }

    @Override
    public OrderDTO finish(OrderDTO orderDTO) {
        //判断订单状态
        if (!OrderStatusEnum.NEW.getCode().equals(orderDTO.getOrderStatus())) {
            log.error("【完结订单】订单状态不正确, orderId={}", orderDTO.getOrderId());
            throw new SellException(ResultEnum.ORDER_STATUS_ERROR);
        }

        //修改订单状态
        Order order = orderRepo.getOne(orderDTO.getOrderId());
        order.setOrderStatus(OrderStatusEnum.FINISHED.getCode());

        order = orderRepo.save(order);

        if (null == order) {
            log.error("【完结订单】更新失败, orderId={}", orderDTO.getOrderId());
            throw new SellException(ResultEnum.ORDER_UPDATE_FAIL);
        }

        BeanUtils.copyProperties(order, orderDTO);

        //推送微信模板消息
        pushMessageService.orderStatus(orderDTO);

        return orderDTO;
    }

    @Override
    public OrderDTO paid(OrderDTO orderDTO) {
        //判断订单状态
        if (!OrderStatusEnum.NEW.getCode().equals(orderDTO.getOrderStatus())) {
            log.error("【订单支付完成】订单状态不正确, orderId={}", orderDTO.getOrderId());
            throw new SellException(ResultEnum.ORDER_STATUS_ERROR);
        }

        //判断支付状态
        if (!orderDTO.getPayStatus().equals(PayStatusEnum.WAIT.getCode())) {
            log.error("【订单支付完成】订单支付状态不正确, orderId={}", orderDTO.getOrderId());
            throw new SellException(ResultEnum.ORDER_PAY_STATUS_ERROR);
        }

        //修改订单状态
        Order order = orderRepo.getOne(orderDTO.getOrderId());
        order.setPayStatus(PayStatusEnum.FINISHED.getCode());
        order = orderRepo.save(order);

        if (null == order) {
            log.error("【订单支付完成】更新失败, orderId={}", orderDTO.getOrderId());
            throw new SellException(ResultEnum.ORDER_UPDATE_FAIL);
        }

        BeanUtils.copyProperties(order, orderDTO);

        return orderDTO;
    }
}
